package com.tpp.order.rabbit;

import com.tpp.comm.pojo.*;
import com.tpp.comm.util.TpConst;
import com.tpp.order.mapper.TaskMapper;
import com.tpp.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 消费订单消息，创建订单
 */
@Component
@RabbitListener(queues = TpConst.Rabbit.ORDER_QUEUE)
@Slf4j
public class ConfirmOrderConsumer {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private OrderService orderService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void confirmOrderConsumer(TpTask task, @Header(AmqpHeaders.DELIVERY_TAG) long tag, Channel channel){
        //存储到本地消息表
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(null);
        task.setStatus(1);
        taskMapper.insert(task);
        //存储订单信息
        try {
            orderService.createOrder(task);
            TpOrder tpOrder = orderService.searchOrder(task.getOrderNo());
            channel.basicAck(tag,true);
            //存入延迟队列中，过期删除
            rabbitTemplate.convertAndSend(TpConst.Rabbit.ORDER_DELAYED_EXCHANGE, TpConst.Rabbit.ORDER_DELAYED_QUEUE, task, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setAppId(tpOrder.getOrderNo());
                    LocalDateTime localDateTime = tpOrder.getCreatedTime().plusMinutes(5);
                    long second = localDateTime.toEpochSecond(ZoneOffset.of("+8"))-LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                    second = second*1000;//获取毫秒
                    message.getMessageProperties().setExpiration(String.valueOf(second));
                    return message;
                }
            });
        } catch (RuntimeException e) {
            try {
                channel.basicReject(tag,false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            log.error(e.getMessage());
            throw new RuntimeException(e);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

    }

}
